var slider;
var isSelectedAll = true;
var chart1 ;
var win ;

var itemCount = 0;
var currentPage = 0;
var currentLeft = 0;
var pageSize = 0;
var pageCount = 0;
var pageWidth = 0;
var foundBrProduct = false;


function doChangeSegment(){
	var min_value = $('#min_price').val() * 1;
	var max_value = $('#max_price').val() * 1;
	$('#left_price').val((min_value*100) + '-' + (max_value*100));
	slider.slider( "values", 0,min_value);
	slider.slider( "values", 1,max_value);
	dosubmit();
}

function gotoPage(page){
  $('#left_p').val(page);
  dosubmit();
}

function orderBy(str){
  $('#left_p').val(1);
  $('#left_o').val(str);
  dosubmit();
  $('#sortContainer>a').each(function(obj){
		$(this).prop("href","javascript:orderBy('"+$(this).attr('oid')+"')").removeClass("active");
  });
  $('#orderby_'+str).addClass("active").prop("href","javascript:void(0);");
}

function filterStore(){
	$('#left_store').val($('#filter_store').prop("checked") ? 1:0);
	dosubmit();
}

function filterLowest(){
	$('#left_lowest').val($('#filter_lowest').prop("checked") ? 1:0);
	dosubmit();
}

function dosubmit(){
	showMessage("正在载入...");
	if(js_segment_min == $('#min_price').val() && js_segment_max == $('#max_price').val()){
		$('#left_price').val('');
	}
	$('#left_selectedAllVendor').val($("#vendor_wrap > :checkbox[checked='false']").length==0 ? 1 : 0);
	$("#search_content").load("/go3c/ajaxSearch.ldo",$('#hideSearchForm').serialize()+"&random="+Math.random(),function(){
		hideMessage();
		refreshFavorite(true);
		refreshSelectCount();
	}); 
}


function selectVendor(vendorId){
	var id = '#checkbox_'+vendorId;
	if(isSelectedAll){
		$('#vendor_wrap > :checkbox').prop("checked", false);
		$('#divVendorIcon>a').addClass("dNo");

		$(id).prop("checked",true);
		$('#link_'+vendorId).removeClass("dNo");
		isSelectedAll = false;
	}else{
		var checked = $(id).prop("checked");
		$(id).prop("checked",!checked);
		$('#link_'+vendorId).toggleClass("dNo");
		isSelectedAll = $("#vendor_wrap > :checkbox[checked='false']").length==0;
	}
	$('#left_p').val(1);
	dosubmit();
}


function selectAllVendors(){
	if(!isSelectedAll){
		$('#vendor_wrap > :checkbox').prop("checked", true); 
		$('#divVendorIcon>a').removeClass("dNo");
		dosubmit();
		isSelectedAll = true;
	}else{
		promptMessage("已经全选");
	}
}

function toggleCategory(){
	$('#search_category').toggle();
	$('#search_category_arrow > span').toggleClass("search_category_close").toggleClass("search_category_open");
}


function selectNoVendors(){
	isSelectedAll = true;
	$('#vendor_wrap > :checkbox').each(function(obj){
		$(this).prop("checked",!$(this).prop("checked"));
	});

	isSelectedAll = $("#vendor_wrap > :checkbox[checked='false']").length==0;

	$('#divVendorIcon>a').each(function(obj){
		$(this).toggleClass("dNo");
	});
	dosubmit();
}

function addToFavoriteClick(){
	if($("#emuserid").length>0){
		showFavoditeDropDown();
	}else{
		openDivLogin();
	}
}


function showFavoditeDropDown(){
	var button = $('#button_addto_favorite');
	var opendiv = $("#opendiv_favorite_dropdown");
	opendiv.load("/passport/favorite/favorite_dropDown.action","random="+Math.random(),function(){
		opendiv.css("zIndex","1000").show();
		opendiv.css("left",button.offset().left);
		opendiv.css("top",button.offset().top +button.height()+4);
		opendiv.css("width",250);
		opendiv.show();
		$('#favorite_name').val($.trim($('#k1').val()).substring(0,15));

		opendiv.mouseup(function() {
                return false
            });

		$(document).mouseup(function(e) {
                if( $(e.target).parent("#button_addto_favorite").length==0 ){
                    opendiv.hide();
                }
            });
	});
}



function showMyFavoriteClick(){
	if($("#emuserid").length>0){
		showMyFavoditeDropDown();
	}else{
		openDivLogin();
	}
}

function showMyFavoditeDropDown(){
	var button = $('#button_my_favorite');
	var opendiv = $("#opendiv_favorite_dropdown");
	opendiv.load("/passport/favorite/favorite_myList.action","random="+Math.random(),function(){
		opendiv.css("zIndex","1000").show();
		opendiv.css("left",button.offset().left);
		opendiv.css("top",button.offset().top +button.height()+4);
		opendiv.css("width",150);
		opendiv.show();

		opendiv.mouseup(function() {
                return false
            });

		$(document).mouseup(function(e) {
                if( $(e.target).parent("#button_my_favorite").length==0 ){
                    opendiv.hide();
                }
            });
	});
}


function addToFavoite(favoriteId){
	var selectedCommodity = $(":checkbox[name='commodityUuid'][checked='true']").length>0;
	if(selectedCommodity){
		$("#opendiv_favorite_dropdown").hide();
		$("#target_favorite_id").val(favoriteId);
		showMessage("正在处理中...");
		$.getJSON("/passport/favorite/favorite_add.action",$('#favorite_form').serialize(),function(data){
				hideMessage();
				if(data.bean.result==true){
         			promptMessage("添加成功!");
					refreshFavorite(true);
				}else{
					promptMessage("添加失败!");
				}
			});
	}else{
		promptMessage("请至少选择一个产品!");;
	}
}

function addToNewFavorite(){
	var selectedCommodity = $(":checkbox[name='commodityUuid'][checked='true']").length>0;
	if(selectedCommodity){
		if($.trim($('#favorite_name').val())!=''){
			$("#opendiv_favorite_dropdown").hide();
			$("#target_favorite_id").val('');
			showMessage("正在处理中...");
			$.getJSON("/passport/favorite/favorite_add.action",$('#favorite_form').serialize(),function(data){
				hideMessage();
				if(data.bean.result==true){
         			promptMessage("添加成功!");
					refreshFavorite(true);
				}else{
					promptMessage("添加失败!");
				}
			});
		}else{
			promptMessage("请输入新收藏夹名称!");
		}
	}else{
		promptMessage("请至少选择一个产品!");
	}
}

function showChart(){
	var selectedCommodity = $(":checkbox[name='commodityUuid'][checked='true']").length>0;
	if(selectedCommodity){
		var chartBox = $('#chart_box');

		var   d   =   document.documentElement;   
		if(!d){
		  d = document.body; 
		}

		var   x   =   Math.ceil((d.clientWidth   -   726)/2)   +   d.scrollLeft;   
		var   y   =   Math.ceil((d.clientHeight   -   360)/2)   +   d.scrollTop;   

		if(y<200) y=200;

		var chartDiv = $("#chartDiv") 
		if(chartDiv.html()!=''){
//			var chart1 = FusionCharts("favoriteChartId");
			chart1 = new FusionCharts("/images/charts/MSLine.swf", "favoriteChartId", "726", "360", "0", "1");
			chart1.setDataURL("/go3c/chart.ldo?"+escape($('#favorite_form').serialize()),"xml");
			chart1.render("chartdiv");
		}else{
			//var chart1 = FusionCharts("favoriteChartId");
			chart1.setXMLUrl("/go3c/chart.ldo?"+escape($('#favorite_form').serialize()),"xml");
			chart1.render("chartdiv");
		}

		chartBox.css("left",x).css("top",y).css("position","absolute").show();

	}else{
		promptMessage("请至少选择一个产品!");
	}
}


function deleteFavorite(id){
	$.getJSON("/passport/favorite/favorite_ajaxDelete.action","id="+id,function(data){
		if(data.bean.result==true){
			promptMessage("删除成功!");
			$("#opendiv_favorite_dropdown").hide();
			refreshFavorite(true);
		}else{
			promptMessage("删除失败!");
		}
	});
}

function ExportMyChart() {
	//var chartObject = getChartFromId('favoriteChartId');
	win = window.open("http://www.boxz.com/wait.html",'sinaweibo', 'location=yes,left=200,top=100,resizable=yes,width=780,height=510');
	win.moveTo(10000,10000);
    if(  chart1.hasRendered()){ 
		chart1.exportChart();
	}else{
		promptMessage("请等待趋势图渲染完毕!");
	}
}

function myChartCallBackFunction(objRtn){
	 if (objRtn.statusCode=="1"){
		var fileName = objRtn.fileName;
		var url = "http://service.t.sina.com.cn/share/share.php?url=http%3A%2F%2Fwww.boxz.com&appkey=&title=TCL+4211CDS+42%E8%8B%B1%E5%AF%B8+1&retcode=0&pic=";
		url += fileName;
		win.moveTo(200,100);
		win.location.href=url;
     } else{
		promptMessage("保存趋势图失败!");
     }
}

function refreshFavorite(clear){
	var objs = $(":checkbox[name='commodityUuid']");
	if(objs.length>0){
		if ($("#emuserid").length>0){
			$.getJSON("/passport/interface/favoriteNames.action",$.param(objs),function(data){
				if(data.status=='1'){
					$.each(data.bean, function(name,value){
						var objId = '#tag_'+name.replace(/@/gi,'_');
						$(objId).addClass("eFavor").attr('title',value);
					});
				}
			});
			if(clear){
				$.each(objs,function(i,obj){
					var objId = '#tag_'+$(obj).val().replace(/@/gi,'_');
					$(objId).removeClass("eFavor").attr('title',"");
				});
			}
		}
	}
}




function openSelectCity(){
	var button = $('#stock_text');
	button.addClass("current");
	var opendiv = $("#popup_city_div");
		opendiv.show();
		opendiv.css("left",button.offset().left+90-opendiv.width());
		opendiv.css("top",button.offset().top + button.height()-1);
		opendiv.show();

		opendiv.mouseup(function() {
                return false
        });

		$(document).mouseup(function(e) {
                if( $(e.target).parent("#popup_city_div").length==0 ){
                    closeSelectCity();
                }
        });

		

}

function closeSelectCity(){
	var button = $('#stock_text');
	button.removeClass("current");
	var opendiv = $("#popup_city_div");
	opendiv.hide();
}

function doSelectCity(districtId,name){
	closeSelectCity();
	$('#left_districtId').val(districtId);
	$('#fav_districtId').val(districtId);
    $('#left_p').val(1);
	$("#favorite_areaId option[value='"+districtId+"']").attr("selected", true);
	addCookie("did",districtId,30);
	dosubmit();
	$('#stock_text').html(name);
	
}


function refreshSelectCount(){
	var selectedCount = $(":checkbox[name='commodityUuid'][checked='true']").length;
	if(selectedCount>0){
		$('#selectedCommodityCount').html('已选 <font color="red">'+selectedCount+'</font> 个商品， 查看');
		$('#button_chart').removeClass('price_chart_off').addClass('price_chart');
		$('#button_chart').parent('a').prop("href","javascript:showChart();");
		$('#button_notice').removeClass('price_notice_off').addClass('price_notice');
		$('#button_notice').parent('a').prop("href","javascript:showNotice();");
	}else{
		$('#selectedCommodityCount').html('可选多个商品，查看');
		$('#button_chart').addClass('price_chart_off').removeClass('price_chart');
		$('#button_chart').parent('a').prop("href","javascript:void(0);");
		$('#button_notice').addClass('price_notice_off').removeClass('price_notice');
		$('#button_notice').parent('a').prop("href","javascript:void(0);");
	}
}


function selectAllCommodity(){
	var selected = $('#commodityIdAll').prop('checked');
	$(":checkbox[name='commodityUuid']").each(function(){
		$(this).prop('checked',selected);
	});
	refreshSelectCount();
}

function doLoginSuccessCallBack(){
	if($("#emuserid").length>0){
		refreshFavorite(true);
		refreshBottomLoginInfo();
	}
}

function showNotice(){
		var chartBox = $('#notict_box');

		var   d   =   document.documentElement;   
		if(!d){
		  d = document.body; 
		}

		var   x   =   Math.ceil((d.clientWidth   -   726)/2)   +   d.scrollLeft;   
		var   y   =   Math.ceil((d.clientHeight   -   360)/2)   +   d.scrollTop;   

		if(y<200) y=200;

		//var noticeChartdiv = $("#noticeChartdiv");
		//if(noticeChartdiv.html()!=''){
//			var chart1 = FusionCharts("favoriteChartId");
			chart2 = new FusionCharts("/images/charts/MSLine.swf", "noticeChartId", "420", "160", "0", "1");
			chart2.setDataURL("/go3c/smallChart.ldo?"+escape($('#favorite_form').serialize()),"xml");
			chart2.render("noticeChartdiv");
		//}

		chartBox.css("left",x).css("top",y).css("position","absolute").show();
		
		if ($("#emuserid").length>0){
			$("#fav_noticetimes_info").html("本通知只发一次.");
			$("#button_user_add_fav").show();
			$("#button_guest_add_fav").hide();
		}else{
			$("#fav_noticetimes_info").html("本通知只发一次.");
			$("#button_user_add_fav").hide();
			$("#button_guest_add_fav").show();
		}

		$("#lowest_info").load("/go3c/lowest.ldo",$('#favorite_form').serialize(),function(data){
			$('#lowPrice').val(subStringBetween(data,'id="fav_current_lowst">','</span>'));
        });
}

function subStringBetween(data,s1,s2) {
   return data.slice(data.search(s1) + s1.length,data.search(s2));
}


function refreshBottomLoginInfo(){
	if ($("#emuserid").length>0){
			$.getJSON("/passport/interface/favoriteCount.action",'',function(data){
				if(data.status=='1'){
					var favoriteCount = "暂无";
					if(data.bean.favoriteCount>0){
						$('#bottom_login_info').html('您有 <a href="/passport/favorite/favorite_list.action" target="_blank">'+data.bean.favoriteCount+'降价通知</a>。');
					}else{
						$('#bottom_login_info').html('您暂无 <a href="/passport/favorite/favorite_list.action" target="_blank">降价通知</a>。');
					}
					
					if(data.bean.mobile){
						$('#mobile').val(data.bean.mobile);
					}
					if(data.bean.email){
						$('#email').val(data.bean.email);
					}
				}
			});
	}

}


function doCreateFavorite(){
	var mailreg=/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/;
	var intReg = /^\+?[1-9][0-9]*$/;　　

	if($('#favorite_name').val() == ""){
		promptMessage("请输入降价通知名称!");
		return;
	}
	if($('#mobile').val() == "" && $('#email').val()==""){
		promptMessage("请至少输入email 或者手机号码!");
		return;
	}
	if(!mailreg.test($("#email").val())){
		promptMessage("请输入正确的email地址!");
		return;
	}
	if(!intReg.test($('#lowPrice').val())){
		promptMessage("请输入正确的价格!");
		return;
	}
	$.getJSON("/passport/interface/favoriteCreate.action",$('#favorite_form').serialize(),function(data){
				if(data.status=='1'){
					promptMessage("保存降价通知成功!");	
					$('#notict_box').hide();
					refreshBottomLoginInfo();
				}
			});

}




function filterStock(postfix){
	$('#left_stock_'+postfix).val($('#filter_stock_'+postfix).prop("checked") ? 1:0);
	dosubmit();
}


function filterShopInShop(postfix){
	$('#left_shop_'+postfix).val($('#filter_shop_'+postfix).prop("checked") ? 1:0);
	dosubmit();
}

/** br product search */
function doright(){
	var page = -1*currentPage;
	if(page<pageCount-1){
		currentPage--;
		currentLeft = currentPage*pageWidth;
		var leftstr = currentLeft +"px"
		$('#brul').animate({'left':leftstr},1000);
		resetButton();
	}
	
}
function doleft(){
	var page = -1*currentPage;
	if(page>0){
		currentPage++;
		currentLeft = currentPage*pageWidth;
		var leftstr = currentLeft +"px"
		$('#brul').animate({'left':leftstr},1000);
		resetButton();
	}
}
function resetButton(){
	var page = -1*currentPage;
	if(page==0)
		$('#buttonLeft').attr("class", "brLeftLinkGray");
	else
		$('#buttonLeft').attr("class", "brLeftLink");
	if(page>=pageCount-1)
		$('#buttonRight').attr("class", "brRightLinkGray");
	else
		$('#buttonRight').attr("class", "brRightLink");
}

function reset(){
	pageSize = Math.floor(($(window).width()-100) / 185);
	pageCount =  Math.ceil(itemCount/pageSize);
	pageWidth = pageSize*185;

	var eleWidth = pageWidth;
	if(eleWidth>$(window).width()){
		eleWidth = $(window).width();
	}
	var strWidth = eleWidth+"px";
	$('#brSearchContent').css({"width":strWidth});
	resetButton();
}
/** br product search */





$(document).ready(function(){

			if(foundBrProduct){
				reset();
				$(window).resize(function() {
					reset();
				});
			}


		    slider = $('#slider').slider({
			range: true,
			min: js_segment_min,
			max:js_segment_max,
			step: 10,
			values: [js_segment_min,js_segment_max],
			slide: function(event, ui) {
				$('#min_price').val(ui.values[0]);
				$('#max_price').val(ui.values[1]);
				//$('#slider_range').html('￥'+ui.values[0] + ' - ￥' + ui.values[1]);
				$('#left_price').val((ui.values[0]*100) + '-' + (ui.values[1]*100));
			},
			stop: function(event, ui) {
				$('#left_p').val(1);
				dosubmit();
			}
		});

		$( "#min_price" ).change(function() {
			var min_value = $('#min_price').val() * 1;
			var max_value = $('#max_price').val() * 1;
//			if(min_value>=js_segment_min){
				if(min_value<=max_value){	
					doChangeSegment();
				}
//			}else{
//				min_value = js_segment_min;
//				$('#min_price').val(min_value);
//			}
		});
		$( "#min_price" ).numeral();
		

		$( "#max_price" ).change(function() {
			var min_value = $('#min_price').val() * 1;
			var max_value = $('#max_price').val() * 1;
			var doChange = false;
//			if(max_value<=js_segment_max){
				if(max_value>=min_value){	
					doChangeSegment();
				}
//			}else{
//				max_value =js_segment_max;
//				$('#max_price').val(max_value);
//				doChangeSegment();
//			}
		});
		$( "#max_price" ).numeral();

		refreshFavorite(false);
		refreshSelectCount();
		

	});

